package com.gitee.feizns.web.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author feizns
 * @since 2019/7/15
 */
public abstract class IOUtils {

    private static final int DEFAULT_BUFF_SIZE = 10240;

    /**
     * 读取流到字符
     * @param is
     * @return
     */
    public static final String readToStr(InputStream is) {
        return new String(readToBytes(is));
    }

    /**
     * 读取流到字节数组
     * @param is
     * @return
     */
    public static final byte[] readToBytes(InputStream is) {
        try(ByteArrayOutputStream bao = new ByteArrayOutputStream()) {
            return transfer(is, bao).toByteArray();
        } catch (IOException e) {
            return new byte[]{ };
        }
    }

    /**
     * 复制流
     * @param is
     * @param size
     * @return
     */
    public static final InputStream[] clone(InputStream is, int size) throws IOException {
        InputStream[] ret = new InputStream[size];
        try ( ByteArrayOutputStream bao = new ByteArrayOutputStream() ) {
            IOUtils.transfer(is, bao);
            for (int i = 0; i < size; i++) {
                ret[i] = new ByteArrayInputStream(bao.toByteArray());
            }
        }
        return ret;
    }

    /**
     * 转移流
     * @param is
     * @param os
     * @param <T>
     * @return
     * @throws IOException
     */
    public static final <T extends OutputStream> T transfer(InputStream is, T os) throws IOException {
        int len = -1;
        byte[] tmp = new byte[DEFAULT_BUFF_SIZE];
        while ( (len = is.read(tmp)) != -1 ) {
            os.write(tmp, 0, len);
        }
        os.flush();
        return os;
    }

}
